package com.rock.code.system.login.service.impl;

import com.rock.code.base.domain.AjaxJson;
import com.rock.code.base.domain.Constants;
import com.rock.code.common.comm.DES3;
import com.rock.code.common.comm.DesEncrypterIsmp;
import com.rock.code.common.comm.MD5;
import com.rock.code.common.exceptions.SystemException;
import com.rock.code.common.spring.SpringCooikes;
import com.rock.code.system.login.service.LoginService;
import com.rock.code.system.user.domain.TbSysLoginmsg;
import com.rock.code.system.user.service.TbSysLoginmsgService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Random;

/**
 * The type Login service.
 *
 * @author kongqiang
 * @date 2017.03.30
 */
@Service
public class LoginServiceImpl implements LoginService {

    /**
     * The Tb sys user service.
     */
    @Resource
    private TbSysLoginmsgService tbSysLoginmsgServiceImpl;


    /**
     * Go login page.
     *
     * @param request the request
     * @author kongqiang
     * @date 2017.03.30
     */
    @Override
    public void goLoginPage(HttpServletRequest request) {
        Cookie remember = WebUtils.getCookie(request, MD5.getMd5(Constants.REMEMBER));
        if (remember != null) {
            WebUtils.setSessionAttribute(request, Constants.REMEMBER, DES3.decode(remember.getValue()));
            Cookie loginCode = WebUtils.getCookie(request, MD5.getMd5(Constants.LOGIN_USER_CODE));
            if (loginCode != null) {
                WebUtils.setSessionAttribute(request, Constants.LOGIN_USER_CODE, DES3.decode(loginCode.getValue()));
                Cookie password = WebUtils.getCookie(request, MD5.getMd5(Constants.LOGIN_USER_PASSWORD));
                if (password != null) {
                    WebUtils.setSessionAttribute(request, Constants.LOGIN_USER_PASSWORD, DES3.decode(DES3.decode(password.getValue())));
                }
            }
        } else {
            request.getSession().removeAttribute(Constants.REMEMBER);
            request.getSession().removeAttribute(Constants.LOGIN_USER_CODE);
            request.getSession().removeAttribute(Constants.LOGIN_USER_PASSWORD);
        }
    }

    /**
     * User login.
     *
     * @param request  the request
     * @param response the response
     * @param param    the param
     * @return the ajax json
     * @throws Exception the exception
     * @author kongqiang
     * @date 2017.03.30
     */
    @Override
    public AjaxJson userLogin(HttpServletRequest request, HttpServletResponse response, Map<String, Object> param) throws Exception {
        AjaxJson ajaxJson = new AjaxJson();
        String msg = "";
        if (StringUtils.isEmpty(param.get("loginCode"))) {
            msg = "登陆ID: 用户名, 邮箱或手机号不能为空!";
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg(msg);
            return ajaxJson;
        }
        if (StringUtils.isEmpty(param.get("password"))) {
            msg = "密码不能为空!";
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg(msg);
            return ajaxJson;
        }
        //// 校验验证码
        //int loginUserErrorNum = StringUtils.isEmpty(WebUtils.getSessionAttribute(request, Constants.LOGIN_USER_ERROR_NUM)) ?
        //        0 : Integer.parseInt(WebUtils.getSessionAttribute(request, Constants.LOGIN_USER_ERROR_NUM).toString());
        //if (loginUserErrorNum > 3) {
            if (StringUtils.isEmpty(WebUtils.getSessionAttribute(request, Constants.SESSION_VALIDATECODE))) {
                if (!WebUtils.getSessionAttribute(request, Constants.SESSION_VALIDATECODE).equals(param.get("user_identify"))) {
                    msg = "验证码错误!";
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg(msg);
                    return ajaxJson;
                }
            }
        //}
        try {
//            param.put("loginPasswd", DES3.encode(param.get("password").toString()));
            param.put("loginPasswd", DesEncrypterIsmp.encrypt(param.get("password").toString()));
            param.put("isDelete", Constants.DELETE_N);
            TbSysLoginmsg loginUser = tbSysLoginmsgServiceImpl.loginByParaMap(param);
//            Base64.Encoder encoder = Base64.getEncoder();
            if (loginUser != null) {
                //记住密码
                if ("on".equals(param.get("remember"))) {
                    //SpringCooikes.addCookie(response, MD5.getMd5(Constants.REMEMBER), DES3.encode(param.get(Constants.REMEMBER).toString()));
                    //SpringCooikes.addCookie(response, MD5.getMd5(Constants.LOGIN_USER_CODE), DES3.encode(param.get(Constants.LOGIN_USER_CODE).toString()));
                    //SpringCooikes.addCookie(response, MD5.getMd5(Constants.LOGIN_USER_PASSWORD), DES3.encode(param.get(Constants.LOGIN_USER_PASSWORD).toString()));
                    String proPassword = DES3.decode(param.get(Constants.LOGIN_USER_PASSWORD).toString());
                    SpringCooikes.addCookie(response, Constants.REMEMBER, param.get(Constants.REMEMBER).toString(), 7*24*60*60);
                    SpringCooikes.addCookie(response, Constants.LOGIN_USER_CODE, param.get(Constants.LOGIN_USER_CODE).toString(), 7*24*60*60);
//                    SpringCooikes.addCookie(response, Constants.LOGIN_USER_PASSWORD, encoder.encodeToString(proPassword.getBytes()), 7*24*60*60);
                } else {
                    //清除Cooike
                    SpringCooikes.delCookie(response, MD5.getMd5(Constants.REMEMBER));
                    SpringCooikes.delCookie(response, MD5.getMd5(Constants.LOGIN_USER_CODE));
                    SpringCooikes.delCookie(response, MD5.getMd5(Constants.LOGIN_USER_PASSWORD));
                }
                // 设置Session信息
                WebUtils.setSessionAttribute(request, Constants.SESSION_USER, loginUser);//放入session
               //TbSysLoginmsg user =  (TbSysLoginmsg) request.getSession().getAttribute(Constants.SESSION_USER);
                msg = "登陆成功!";
                ajaxJson.setMsg(msg);
                return ajaxJson;
            } else {
                msg = "用户名或密码不正确!";
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg(msg);
                //Map<String, Object> attrbutes = new HashMap<String, Object>();
                //attrbutes.put(Constants.LOGIN_USER_ERROR_NUM, loginUserErrorNum + 1);
                //ajaxJson.setAttributes(attrbutes);
                //WebUtils.setSessionAttribute(request, Constants.LOGIN_USER_ERROR_NUM, loginUserErrorNum + 1);//放入session
                return ajaxJson;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException("系统异常", e);
        }
    }

    /**
     * Generate captcha.
     *
     * @param request the request
     * @param output  the output
     * @author kongqiang
     * @date 2017.03.30
     */
    @Override
    public void generateCaptcha(HttpServletRequest request, ByteArrayOutputStream output) {
        String code = this.drawImg(output);
        WebUtils.setSessionAttribute(request, Constants.SESSION_VALIDATECODE, code);//放入session
    }

    /**
     * Draw img.
     *
     * @param output the output
     * @return the string
     * @author kongqiang
     * @date 2017.03.30
     */
    private String drawImg(ByteArrayOutputStream output) {
        String code = "";
        for (int i = 0; i < 4; i++) {
            code += randomChar();
        }
        int width = 70;
        int height = 25;
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Font font = new Font("Times New Roman", Font.PLAIN, 20);
        Graphics2D g = bi.createGraphics();
        g.setFont(font);
        Color color = new Color(66, 2, 82);
        g.setColor(color);
        g.setBackground(new Color(226, 226, 240));
        g.clearRect(0, 0, width, height);
        FontRenderContext context = g.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(code, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = bounds.getY();
        double baseY = y - ascent;
        g.drawString(code, (int) x, (int) baseY);
        g.dispose();
        try {
            ImageIO.write(bi, "jpg", output);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * Random char.
     *
     * @return the char
     * @author kongqiang
     * @date 2017.03.30
     */
    private char randomChar() {
        Random r = new Random();
        String s = "0123456789";
        return s.charAt(r.nextInt(s.length()));
    }
}